// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-15

package name

import (
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
	"server/app/lib"
)

// Logic
// 保存钓场名称.
type Logic struct {
	admin   *models.ArcadeAdmins
	arcade  *models.Arcades
	affects int64

	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// After
// 后置结果.
func (o *Logic) After(ctx context.Context, _ iris.Context, _ result.Result) {
	if o.affects > 0 {
		_, _ = services.NewArcadeLogsService().Add(ctx,
			o.arcade, o.admin, kind.ArcadeAdminOperationUpdateArcadeName, kind.ArcadeAdminOperationUpdateArcadeName.ToUpdateArcadeName(
				o.arcade.Name, o.request.Name,
			),
		)
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Json(i, o.request); err == nil {
		o.arcade, o.admin = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err error
		res = result.New()
	)

	if o.affects, err = services.NewArcadesService().Dao.UpdateFieldsById(ctx, map[string]any{
		"name": o.request.Name,
	}, o.arcade.Id); err != nil {
		return res.WithError(err)
	}

	o.response.Name = o.request.Name
	return res.With(o.response)
}
